package com.netmi.myuploadfileretrofit.http;

import com.netmi.myuploadfileretrofit.inteface.ReqProgressCallBack;

import java.io.IOException;

import io.reactivex.annotations.Nullable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * 类描述：重写RequestBody 监听下载进度，通过拦截器 调用 然后接口返回数据
 * 创建人：tgw
 * 创建时间：2020/7/27
 * 修改备注：
 */
public class ProgressResponseBody extends RequestBody {

    private RequestBody mRequestBody;
    private BufferedSource mBufferedSource;
    private CountingSink mCountingSink;
    private ReqProgressCallBack callBack;

    public ProgressResponseBody(RequestBody body, ReqProgressCallBack callBack) {
        this.mRequestBody = body;
        this.callBack = callBack;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return mRequestBody.contentType();
    }

    @Override
    public long contentLength() {
        try {
            return mRequestBody.contentLength();
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }

    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        BufferedSink bufferedSink;

        mCountingSink = new CountingSink(sink);
        bufferedSink = Okio.buffer(mCountingSink);

        mRequestBody.writeTo(bufferedSink);
        bufferedSink.flush();


    }


    class CountingSink extends ForwardingSink {


        //当前写入字节数
        long currentSize = 0L;
        //总字节长度，避免多次调用contentLength()方法
        long totalSize = 0L;

        public CountingSink(Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);

            if (totalSize == 0) {
                //获得contentLength的值，后续不再调用
                totalSize = contentLength();
            }
            //增加当前写入的字节数
            currentSize += byteCount;
            //当前上传的百分比进度
            int progress = (int) (currentSize * 100 / totalSize);


            if (callBack != null) {
                callBack.onProgress(currentSize, contentLength());
            }
        }
    }


}
